from rest_framework import serializers
from django_redis import get_redis_connection


# class SendSmsSerializer1(serializers.Serializer):
#     mage_code_id = serializers.UUIDField()
#     text = serializers.CharField(max_length=4, min_length=4)
#     '''因为is_valid中　　他自动会校验，所以不需要判断是否为４位数的验证码，
#     现将redis中的text数据取出来，判断是否过期，完了之后在判断是否为一致，
#     在判断是否为１分钟之内
#     serializers.ValidationError('请求次数过于频繁')'''
#
#     def validate(self, attrs):
#         print("1234532356432345643234234234234234")
#         mage_code_id = attrs['image_code_id']
#         text = attrs['text']
#         # 之所以不需要捕获异常，因为APIView自动会捕获异常，我们又重写了重写了他的方法，所以不需要
#         redis_conn = get_redis_connection('verify_codes')
#         new_text = redis_conn.get(mage_code_id)
#         print("123123123123123123123")
#         if not new_text:
#             raise serializers.ValidationError('图片验证码无效')
#
#         print(text, new_text.decode())
#         if text.lower() != new_text.decode().lower():
#             raise serializers.ValidationError('图片验证码错误')
#
#         mobile = self.context['view'].kwargs['mobile']
#         send_flag = redis_conn.get(mobile)
#         if send_flag:
#             raise serializers.ValidationError('１分钟之内不能在此发送验证码')
#         return attrs



class SendSmsSerializer(serializers.Serializer):
    """
    图片验证码校验序列化器
    """
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    def validate(self, attrs):
        """
        校验
        """
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        # 查询真实图片验证码
        redis_conn = get_redis_connection('verify_codes')
        real_image_code_text = redis_conn.get(str(image_code_id))
        if not real_image_code_text:
            raise serializers.ValidationError('图片验证码无效')

        # 删除图片验证码
        redis_conn.delete('img_%s' % image_code_id)

        # 比较图片验证码
        real_image_code_text = real_image_code_text.decode()
        if real_image_code_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 判断是否在60s内
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            raise serializers.ValidationError('请求次数过于频繁')
        return attrs
